import React, { useContext, useMemo, useState } from "react";

const UserContext = React.createContext({ auth: false });

function Nav() {
	return (
		<div className='nav'>
			<UserButton />
		</div>
	);
}

function UserButton() {
	const { user, setUser } = useContext(UserContext);
	console.log("userButton render");
	return (
		<button
			onClick={() => {
				if (user.auth) {
					setUser({ auth: false });
				} else {
					setUser({ auth: true, name: "张三" });
				}
			}}>
			{user.auth ? `${user.name} 登出` : "登录"}
		</button>
	);
}

export default function ChangeContextDemo() {
	const [user, setUser] = useState({ auth: false });
	//const contextValue = [user,setUsers]
	const contextValue = useMemo(() => ({ user, setUser }), [user]);
	const [count, setCount] = useState(0);
	return (
		<div>
			<UserContext.Provider value={contextValue}>
				<Nav />
				<button onClick={() => setCount(count + 1)}>click{count}</button>
			</UserContext.Provider>
		</div>
	);
}
